package com.kevin.i18n.dynamic.configuration.component;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.kevin.i18n.dynamic.model.Language;
import com.kevin.i18n.dynamic.service.LanguageService;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.Locale;

@Component
public class I18nDynamicAdapter {

    @Resource
    private LanguageService languageService;

    public Language dynamicMessage(Locale locale, String code) {
        String local = (null != locale) ? locale.toLanguageTag() : Locale.getDefault().toLanguageTag();
        LambdaQueryWrapper<Language> wrapper = Wrappers.<Language>lambdaQuery()
                .eq(Language::getLocale, local)
                .eq(StringUtils.isNotEmpty(code), Language::getCode, code);
        Language language = this.languageService.getOne(wrapper);
        return (null != language) ? language : new Language().setLocale(local).setCode(code);
    }

}
